package com.yycx.module.bus.provider.handler.haiying.tasktodo.settle.pay;

import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.constants.CommonConstants;
import com.yycx.common.utils.DateUtils;
import com.yycx.module.bus.client.entity.BusOrderDetails;
import com.yycx.module.bus.client.entity.BusPayment;
import com.yycx.module.bus.client.enums.AmountTypeEnum;
import com.yycx.module.bus.provider.service.BusOrderDetailsService;
import com.yycx.module.bus.provider.service.BusPaymentService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * 资金支付审批结束监听器
 *
 * @author zyf
 */
@Component
public class HyPayPaymentProcessEndListener implements ExecutionListener {
    @Resource
    private BusPaymentService paymentService;
    @Resource
    private BusOrderDetailsService orderDetailsService;

    @Override
    public void notify(DelegateExecution delegateExecution) {
        String businessKey = delegateExecution.getProcessInstanceBusinessKey();
        String payDate = delegateExecution.getVariable("payDate", String.class);
        BusPayment payment = paymentService.getById(businessKey);
        String amountType = payment.getAmountType();
        paymentService.updatePaymentState(Long.parseLong(businessKey), CommonConstants.INT_2);
        //退保证金
        if (AmountTypeEnum.CbReturn.getCode().equals(amountType)) {
            Long paymentId = payment.getPaymentId();
            if (FlymeUtils.isNotEmpty(paymentId)) {
                List<BusOrderDetails> list=orderDetailsService.selectByTbzjId(paymentId);

                if(FlymeUtils.isNotEmpty(list)){
                    for (BusOrderDetails orderDetails : list) {
                        BigDecimal customBond=orderDetails.getCustomBond();
                        BigDecimal overAmount=FlymeUtils.getBigDecimal(orderDetails.getCustomOverBond(),"0");
                        BigDecimal returnAmount=customBond.add(overAmount);
                        //更新为已退款
                        orderDetailsService.updateReturnCustomBond(orderDetails.getOrderDetailsId(),returnAmount, payDate);
                    }
                }

            }
        }
    }
}
